package com.xander.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xander.entity.Cookie;
import com.xander.entity.Link;

/**
 * Created by YE on 2018/5/3.
 */
public class LuckyMoneyUtils {

    //设置抢红包要发送的json
    public static JSONObject setGrabJson(Link link, Cookie cookie, String number) {
        number=PhoneNumberUtils.asteriskNumber(number);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("device_id", "");
        jsonObject.put("hardware_id", "");
        jsonObject.put("method", "phone");
        jsonObject.put("group_sn", link.getSn());
        jsonObject.put("sign", cookie.getElemeKey());
        jsonObject.put("phone", "");
        jsonObject.put("platform", link.getPlatform());
        jsonObject.put("track_id", cookie.getTrackId()==null?"undefined":cookie.getTrackId());
        jsonObject.put("weixin_avatar", cookie.getAvatar());
        jsonObject.put("weixin_username", number);
        jsonObject.put("unionid", "fuck");
        return jsonObject;
    }

    //设置修改手机要发送的json
    public static JSONObject setChangeJson(Cookie cookie, String phoneNumber) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sign", cookie.getElemeKey());
        jsonObject.put("phone", phoneNumber);
        return jsonObject;
    }

    //通过url cookie 抢红包
    public static String grabOne(Link link, Cookie cookie, String number) {
        JSONObject jsonObject=setGrabJson(link, cookie, number);
        System.out.println(jsonObject);
        //合成链接
        StringBuffer reqgraburl = new StringBuffer("https://h5.ele.me/restapi/marketing/promotion/weixin/");
        reqgraburl.append(cookie.getOpenid());
        String result = ConnectionUtils.httpUrlConnection(jsonObject, reqgraburl.toString(), "POST");
        return result;
    }

    //修改手机号（不返回数据）
    public static boolean changePhone(Cookie cookie, String phoneNumber) {
        JSONObject changeJson = setChangeJson(cookie, phoneNumber);
        StringBuffer reqchangeurl = new StringBuffer("https://h5.ele.me/restapi/v1/weixin/");
        reqchangeurl.append(cookie.getOpenid());
        reqchangeurl.append("/phone");
        String result=ConnectionUtils.httpUrlConnection(changeJson, reqchangeurl.toString(), "PUT");
        if (result.equals("204")) {
            return true;
        } else {
            return false;
        }
    }

    //获得已经领取的次数
    public static int getGrabNum(String data) {
        JSONObject obj = JSONObject.parseObject(data);
        //红包已经领取次数
        JSONArray promotion_records =obj.getJSONArray("promotion_records");
        return promotion_records.size();
    }
}